import { getUrl } from './util';
const app = getApp(); // 引入app
// 根据路由显示不同的加载文字

let degree = 0;

const setTitle = (url) => {
    let title = '加载中';

    switch (url) {
        case '/user/login':
            title = '登陆中';
            break;

        case '/user/loginWXAdds':
            title = '登陆中';
            break;

        default:
            break;
    }

    return title;
}; // 防止重复弹出Modal

const onLogin = (e) => {
    if (e == 1) {
        uni.setStorageSync('token', '');
        uni.setStorageSync('_shopmalladdress', '');
        uni.showModal({
            title: '您还未登录',
            content: '请先登录再进行操作',

            success(res) {
                if (res.confirm) {
                    getUrl();
                    toLogin(); // wx.reLaunch({
                    //     url: '/firstpages/authorization/index',
                    // })

                    degree = 0;
                } else if (res.cancel) {
                    degree = 0;
                }
            }
        });
    } else if (e == 2) {
        // 完善资料
        uni.showModal({
            title: '您还未进行完善资料',
            content: '为了完整的进行体验，请先完成完善资料再进行操作。',
            cancelText: '暂不完善',
            confirmText: '立即完善',

            success(res) {
                if (res.confirm) {
                    uni.reLaunch({
                        url: '/firstpages/information/index'
                    });
                    degree = 0;
                } else if (res.cancel) {
                    degree = 0;
                }
            }
        });
    } // else if (e == 3) {
    //     // 认证
    //     wx.showModal({
    //         title: '您还未进行认证',
    //         content: '为了完整的进行体验，请先完成认证再进行操作。',
    //         cancelText: '暂不认证',
    //         confirmText: '立即认证',
    //         success(res) {
    //             if (res.confirm) {
    //                 wx.reLaunch({
    //                     url: '/firstpages/information/index',
    //                 })
    //                 // wx.reLaunch({
    //                 //     url: '/pages/login/index',
    //                 // })
    //                 degree = 0
    //             } else if (res.cancel) {
    //                 degree = 0
    //             }
    //         }
    //     })
    // }
}; // 信息认证

const onAuth = () => {
    uni.showModal({
        title: '您还未进行信息认证',
        content: '为了完整的进行体验，请先完成信息认证再进行操作。',
        cancelText: '暂不认证',
        confirmText: '立即认证',

        success(res) {
            if (res.confirm) {
                uni.navigateTo({
                    url: '/pages/auth/index'
                });
                degree = 0;
            } else if (res.cancel) {
                degree = 0;
            }
        }
    });
}; //处理登录

const toLogin = () => {
    // 查看是否授权
    uni.getSetting({
        success: function (res) {
            //已授权直接登录
            if (res.authSetting['scope.userInfo']) {
                uni.getUserInfo({
                    success: function (res) {
                        // 根据自己的需求有其他操作再补充
                        // 我这里实现的是在用户授权成功后，调用微信的 wx.login 接口，从而获取code
                        uni.login({
                            success: (res) => {
                                // 获取到用户的 code 之后：res.code}
                                // console.log(res.code,'res.code');
                                getwxAppletlogin(res.code);
                            }
                        });
                    }
                });
            } else {
                // 用户没有授权
                uni.reLaunch({
                    url: '/firstpages/authorization/index'
                });
            }
        }
    });
};

const getwxAppletlogin = (code) => {
    get('/storeUser/wxAppletlogin', {
        code: code,
        client: 'Applet'
    }).then((res) => {
        if (res.data.data.id) {
            uni.setStorageSync('userid', res.data.data.id);
            uni.setStorageSync('user', res.data.data);
            uni.setStorageSync('token', res.data.data.token);
            uni.setStorageSync('userId', res.data.data.id);

            if (uni.getStorageSync('code')) {
                this.onSubmitcode(res.data.data.id);
            }

            if (res.data.data.storeId && res.data.data.storeId != null) {
                // 存在说明已经成为门店
                uni.setStorageSync('storeId', res.data.data.storeId);
                let router = uni.getStorageSync('Router');
                let url = uni.getStorageSync('Url');

                if (url || router) {
                    if (router.startsWith('/firstpages')) {
                        uni.reLaunch({
                            url: router
                        });
                    } else {
                        uni.reLaunch({
                            url: url
                        });
                    }

                    uni.removeStorageSync('Router');
                    uni.removeStorageSync('Url');
                } else {
                    uni.reLaunch({
                        url: '/firstpages/home/index'
                    });
                }
            } else {
                // 如果没有美发师id就去完善资料
                uni.reLaunch({
                    url: '/firstpages/information/index'
                });
            }
        } else {
            uni.reLaunch({
                url: '/firstpages/authorization/index'
            });
        }
    });
}; //-------------------------------

const onSubmitcode = (id) => {
    postObj('/recomUser/bindInviteCode', {
        userId: id,
        invitecode: uni.getStorageSync('code')
    }).then((res) => {
        uni.removeStorageSync('code');
    });
};

const retard = (e) => {
    onLogin(e);
    ++degree;
}; //上次弹窗时间, 3分钟内只能显示一次

let lastTime = 0;

const request = (url, options) => {
    return new Promise((resolve, reject) => {
        // 监听网络状态，失败则跳转网络失败页面
        uni.onNetworkStatusChange(function (res) {
            const distanceTime = new Date().getTime() - lastTime;
            console.log(distanceTime, 'distanceTime');

            if (res.isConnected == false && res.networkType == 'none' && distanceTime > 1000 * 60 * 3) {
                lastTime = new Date().getTime();
                uni.navigateTo({
                    url: '/pages/networkanomaly/index'
                });
            }
        }); // 弱网检测
        // wx.onNetworkWeakChange(function (res) {
        //     if(res.weakNet){
        //         wx.navigateTo({
        //             url: '/pages/networkanomaly/index',
        //         })
        //     }
        // })
        // 加载状态文字

        uni.showLoading({
            title: setTitle(url)
        });
        var requesturl = app.globalData.baseurl;
        uni.request({
            url: `${requesturl}${url}`,
            method: options.method,
            data: options.data,
            header: {
                'content-type': options.isObj ? 'application/json' : 'application/x-www-form-urlencoded',
                token: uni.getStorageSync('token') ? uni.getStorageSync('token') : ''
            },

            success(request) {
                uni.hideLoading();
                uni.hideToast(); // 取消监听
                // wx.offNetworkWeakChange()

                resolve(request);

                if (request.data.code !== 200) {
                    // if ((request.data.code === 300 && degree == 0) && !wx.getStorageSync('userId')) {
                    if (request.data.code === 300 && degree == 0) {
                        uni.showToast({
                            title: request.data.message,
                            icon: 'none',
                            duration: 2000
                        });
                        retard(1);
                    } else if (!uni.getStorageSync('storeId') && degree == 0 && uni.getStorageSync('userId')) {
                        retard(2);
                    } // else if((wx.getStorageSync('authtype') == 3 && wx.getStorageSync('userId')) && (wx.getStorageSync('storeId') && degree == 0)){
                    //     retard(3)
                    // }
                } else {
                    // wx.showToast({
                    //     title: request.data.message,
                    //     icon: 'none',
                    //     duration: 2000
                    // })
                }
            },

            fail(error) {
                console.log(error, 'error');
                reject(error.data);
                uni.hideLoading();
            } // complete: () => {
            //     setTimeout(() => {
            //         wx.hideLoading();
            //     }, 100);
            // }
        });
    });
};

const get = (url, options, type) => {
    if (!type) {
        url = app.globalData.storePrefix + url;
    } else if (type === app.globalData.mallType) {
        url = app.globalData.mallPrefix + url;
    } else if (type === app.globalData.msgType) {
        url = app.globalData.msgPrefix + url;
    } else if (type === app.globalData.userType) {
        url = app.globalData.userPrefix + url;
    } else if (type === app.globalData.yiyueType) {
        url = app.globalData.yiyuePrefix + url;
    } else {
        url = url;
    }

    if (!options) {
        options = {};
    }

    return request(url, {
        method: 'GET',
        data: options
    });
}; //post对象

const postObj = (url, options, type) => {
    if (!type) {
        url = app.globalData.storePrefix + url;
    } else if (type === app.globalData.mallType) {
        url = app.globalData.mallPrefix + url;
    } else if (type === app.globalData.msgType) {
        url = app.globalData.msgPrefix + url;
    } else if (type === app.globalData.userType) {
        url = app.globalData.userPrefix + url;
    } else if (type === app.globalData.yiyueType) {
        url = app.globalData.yiyuePrefix + url;
    }

    return request(url, {
        method: 'POST',
        data: options,
        isObj: options.isObj ? false : true
    });
}; //post参数

const post = (url, options, type) => {
    if (!type) {
        url = app.globalData.storePrefix + url;
    } else if (type === app.globalData.mallType) {
        url = app.globalData.mallPrefix + url;
    } else if (type === app.globalData.msgType) {
        url = app.globalData.msgPrefix + url;
    } else if (type === app.globalData.userType) {
        url = app.globalData.userPrefix + url;
    } else if (type === app.globalData.yiyueType) {
        url = app.globalData.yiyuePrefix + url;
    }

    return request(url, {
        method: 'POST',
        data: options,
        isObj: false
    });
};

const put = (url, options, type) => {
    if (!type) {
        url = app.globalData.storePrefix + url;
    } else if (type === app.globalData.mallType) {
        url = app.globalData.mallPrefix + url;
    } else if (type === app.globalData.msgType) {
        url = app.globalData.msgPrefix + url;
    } else if (type === app.globalData.userType) {
        url = app.globalData.userPrefix + url;
    } else if (type === app.globalData.yiyueType) {
        url = app.globalData.yiyuePrefix + url;
    }

    return request(url, {
        method: 'PUT',
        data: options
    });
}; // 不能声明DELETE（关键字）

const remove = (url, options, type) => {
    if (!type) {
        url = app.globalData.storePrefix + url;
    } else if (type === app.globalData.mallType) {
        url = app.globalData.mallPrefix + url;
    } else if (type === app.globalData.msgType) {
        url = app.globalData.msgPrefix + url;
    } else if (type === app.globalData.userType) {
        url = app.globalData.userPrefix + url;
    } else if (type === app.globalData.yiyueType) {
        url = app.globalData.yiyuePrefix + url;
    }

    return request(url, {
        method: 'DELETE',
        data: options
    });
};

module.exports = {
    get,
    post,
    put,
    remove,
    postObj
};
